package com.m4f.city.business.service.impl;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;
import java.util.logging.Logger;

import com.m4f.city.business.domain.Organization;
import com.m4f.city.business.service.ifc.OrganizationService;
import com.m4f.gaeweb.business.service.impl.DAOBaseService;
import com.m4f.gaeweb.persistence.dao.ifc.DAOSupport;

public class OrganizationServiceImpl extends DAOBaseService implements OrganizationService {
	
	private static final Logger LOGGER = Logger.getLogger(OrganizationServiceImpl.class.getName());
	
	public OrganizationServiceImpl(DAOSupport dao) {
		super(dao);
	}

	@Override
	public long countOrganization() throws Exception {
		return this.DAO.count(Organization.class);
	}

	@Override
	public Organization createOrganization() {
		return this.DAO.createInstance(Organization.class);
	}

	@Override
	public void delete(Organization organization) throws Exception {
		this.DAO.delete(organization);
	}

	@Override
	public List<Organization> getAllOrganization() throws Exception {
		return this.DAO.findAll(Organization.class);
	}

	@Override
	public Organization getOrganization(Long id) throws Exception {
		return (Organization) this.DAO.findById(Organization.class, id);
	}

	@Override
	public Collection<Organization> getOrganizationsByRange(String ordering,
			int init, int end) throws Exception {
		return this.DAO.findEntitiesByRange(Organization.class, ordering, init, end);
	}
	
	@Override
	public Collection<Organization> getOrganizationsByRange(String ordering, String filterBy, String filterValue, int init, int end) throws Exception {
		
		// TODO TESTING FOR USE IT IN TABLES!!
		if(filterBy != null && filterValue != null && !("").equals(filterBy) && !("").equals(filterValue)) {			
			String filter = filterBy + " >= " + " param " + " && " + filterBy + " < " + " hack ";
			String typeParam = "java.lang.String ";
			
			String hack =  filterValue + "\ufffd";
			try {
				Field field = Organization.class.getDeclaredField(filterBy);
				typeParam = field.getType().getCanonicalName();
				String param = typeParam + " param, " + typeParam + " hack ";
				Constructor constructor = field.getType().getConstructor(filterValue.getClass());
				Object value = constructor.newInstance(new Object[] {filterValue});
				Object[] values = new Object[] {value, hack};
				
				return this.DAO.findEntitiesByRange(Organization.class, filter, param, values, filterBy, init, end);
			} catch(Exception e) {
				e.printStackTrace();				
			}
			
		} 
		
		return this.DAO.findEntitiesByRange(Organization.class, ordering, init, end);
	}

	@Override
	public void save(Organization organization) throws Exception {
		this.DAO.saveOrUpdate(organization);
	}
}